<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\CssSelector\Exception\InternalErrorException;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Goods extends Model
{
	use HasDateTimeFormatter;
	protected $fillable = [
	    "name","img","flash_sale_price","on_sale","discounts",
        "flash_sale_number","flash_sale_start_time","flash_sale_end_time"
    ];
	protected $dates = ['flash_sale_start_time','flash_sale_end_time'];

	//商品分类
	public function goodsCategory(){
	    return $this->belongsTo(GoodsCategory::class);//
    }
//    //所属作家
//    public function author(){
//        return $this->belongsTo(Author::class);
//    }
    //所属作家
    public function authors():BelongsToMany
    {
        $pivotTable = 'author_good'; // 中间表

        $relatedModel = Author::class; // 关联模型类名

        return $this->belongsToMany($relatedModel, $pivotTable, 'good_id', 'author_id');
//        return $this->belongsToMany(Author::class);
    }
    //商品详情
    public function goodsContent(){
	    return $this->hasOne(GoodsContent::class);
    }
    //商品图册
    public function goodsImages(){
	    return $this->hasMany(GoodsImage::class);
    }
    //用户查看记录
    public function goodsWatchLogs(){
	    return $this->hasMany(GoodsWatchLogs::class);
    }

//    //收藏产品的人
    public function collectionUsers(){
        return $this->hasMany(GoodsCollection::class);
    }
    //咨询产品的人
    public function userAskForGoods(){
	    return $this->hasMany(UserAskForGoods::class);
    }
    // 定义一个public方法访问图片或文件
//    public function getImage()
//    {
//        if (Str::contains($this->img, '//')) {
//            return $this->img;
//        }
//
//        return Storage::disk('admin')->url($this->img);
//    }

// 定义一个名为 is_before_start 的访问器，当前时间早于秒杀开始时间时返回 true
    public function getIsBeforeStartAttribute()
    {
        return Carbon::now()->lt($this->flash_sale_start_time);
    }

    // 定义一个名为 is_after_end 的访问器，当前时间晚于秒杀结束时间时返回 true
    public function getIsAfterEndAttribute()
    {
        return Carbon::now()->gt($this->flash_sale_end_time);
    }


    //商品减少库存
    public function decreaseSku($amount){
	    if ($amount<0){
	        throw new InternalErrorException("减少的库存不可小于0");
        }
	    return $this->where("id",$this->id)
                ->where("sku",">=",$amount)
                ->decrement("sku",$amount);
    }
}
